package com.api.sw.duban.util;

import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.ConnectionPool;
import weaver.conn.RecordSetTrans;
import weaver.conn.WeaverConnection;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.interfaces.datasource.DataSource;

public class SqlUtil {
	private final static LogTool log1 = new LogTool("/log/assetlog/luolf/SqlUtil",false);
    private ConnectionPool pool = ConnectionPool.getInstance();
    private WeaverConnection conn1;

    public boolean getConnection(String var1) {
        try {
            if (var1 != null) {
                this.conn1 = this.pool.getConnection(var1);
            } else {
                this.conn1 = this.pool.getConnection();
            }

            return this.conn1 != null;
        } catch (Exception var3) {

            return false;
        }
    }
	public static boolean executeUpdateListTran(String datesource, List<Map<String,Object>> list){
        boolean flag=true;
        DataSource ds =null;
        Connection conn = null;
        PreparedStatement stmt =null;
        //获取HR数据源
        try {
            ds = (DataSource) StaticObj.getServiceByFullname(("datasource."+datesource), DataSource.class);
            conn = ds.getConnection();
            conn.setAutoCommit(false);
            for(Map<String,Object> sqls:list) {
                if(sqls==null||sqls.size()<=0){
                    continue;
                }
                String sql=(String)sqls.get("sql");
                log1.writeLog("executeUpdateListTran--->"+sql);
                Object[] params=(Object[])sqls.get("params");
                log1.writeLog("executeUpdateListTran--->"+params.length);
                stmt = conn.prepareStatement(sql);
                //设置手工提交

                if (params != null && params.length > 0) {
                    int i = 1;
                    for (Object para : params) {
                        if (((para instanceof Integer)) || ((para instanceof Long))) {
                            stmt.setInt(i, Util.getIntValue("" + para));
                        } else if ((para instanceof Float)) {
                            stmt.setFloat(i, Util.getFloatValue("" + para));
                        } else if (((para instanceof BigDecimal)) || ((para instanceof Double))) {
                            if ((para instanceof BigDecimal)) {
                                stmt.setBigDecimal(i, (BigDecimal) para);
                            } else {
                                double tBig = Util.getDoubleValue("" + para);
                                // BigDecimal temp=new BigDecimal(tBig);
                                if(tBig==0){
                                    stmt.setString(i, null);
                                }else {
                                    stmt.setString(i, doubleToStr(tBig));
                                }
                            }
                        } else if ((para instanceof Date)) {
                            stmt.setDate(i, (Date) para);
                        } else if (((para instanceof String)) || ((para instanceof Character))) {
                            stmt.setString(i, "" + para);
                        } else if (para == null) {
                            stmt.setNull(i, 0);
                        } else if ((para instanceof Clob)) {
                            stmt.setClob(i, (Clob) para);
                        } else if ((para instanceof Blob)) {
                            stmt.setBlob(i, (Blob) para);
                        } else {
                            stmt.setObject(i, para);
                        }
                        i++;
                    }
                }
                int len = stmt.executeUpdate();
                log1.writeLog("len--->"+len);
                if (len > 0) {
                    flag = true;
                } else {
                    flag = false;
                    stmt.close();
                    conn.rollback();
                    break;
                }
            }
            conn.commit();
            conn.close();
        }catch (Exception e){
            log1.writeLog("executeUpdateListTranException"+e.getMessage());
            try {
                conn.rollback();
                conn.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
            flag=false;
        }
        return flag;
    }
    public  boolean executeUpdateListTranRec( List<Map<String,Object>> list){
        boolean flag=true;
        PreparedStatement stmt =null;
        //获取HR数据源
        try {
            if(getConnection("")){


            RecordSetTrans var1 = new RecordSetTrans();
            var1.setAutoCommit(false);

            //conn = ds.getConnection();
            //conn.setAutoCommit(false);
            for(Map<String,Object> sqls:list) {
                if(sqls==null||sqls.size()<=0){
                    continue;
                }
                String sql=(String)sqls.get("sql");
                log1.writeLog("executeUpdateListTran--->"+sql);
                Object[] params=(Object[])sqls.get("params");
                log1.writeLog("executeUpdateListTran--->"+params.length);
                stmt = conn1.prepareStatement(sql);
                //设置手工提交

                if (params != null && params.length > 0) {
                    int i = 1;
                    for (Object para : params) {
                        if (((para instanceof Integer)) || ((para instanceof Long))) {
                            stmt.setInt(i, Util.getIntValue("" + para));
                        } else if ((para instanceof Float)) {
                            stmt.setFloat(i, Util.getFloatValue("" + para));
                        } else if (((para instanceof BigDecimal)) || ((para instanceof Double))) {
                            if ((para instanceof BigDecimal)) {
                                stmt.setBigDecimal(i, (BigDecimal) para);
                            } else {
                                double tBig = Util.getDoubleValue("" + para);
                                // BigDecimal temp=new BigDecimal(tBig);
                                if(tBig==0){
                                    stmt.setString(i, null);
                                }else {
                                    stmt.setString(i, doubleToStr(tBig));
                                }
                            }
                        } else if ((para instanceof Date)) {
                            stmt.setDate(i, (Date) para);
                        } else if (((para instanceof String)) || ((para instanceof Character))) {
                            stmt.setString(i, "" + para);
                        } else if (para == null) {
                            stmt.setNull(i, 0);
                        } else if ((para instanceof Clob)) {
                            stmt.setClob(i, (Clob) para);
                        } else if ((para instanceof Blob)) {
                            stmt.setBlob(i, (Blob) para);
                        } else {
                            stmt.setObject(i, para);
                        }
                        i++;
                    }
                }
                int len = stmt.executeUpdate();
                log1.writeLog("len--->"+len);
                if (len > 0) {
                    flag = true;
                } else {
                    flag = false;
                    stmt.close();
                    conn1.rollback();
                    break;
                }
            }
            conn1.commit();
            conn1.close();
            }else{
                log1.writeLog("executeUpdateListTranException---connException ");
            }
        }catch (Exception e){
            log1.writeLog("executeUpdateListTranException"+e.getMessage());
            try {
                conn1.rollback();
                conn1.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
            flag=false;
        }
        return flag;
    }
	/**
     * java dobule数据转字符串输出
     * @param tempX 需要被转换的数据
     * @return 默认保留4位小数输出
     */
    public static String doubleToStr(double tempX) {
        double newStemp=round(tempX, 2);
        DecimalFormat df = new DecimalFormat("0.00");
        String newff = df.format(newStemp);
        return newff;
    }
    /**
     * 四舍五入
     * @param v
     * @param scale 精确位数
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /**
     * 四舍五入
     * @param v
     * @param scale 精确位数
     */
    public static float roundF(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }
    /*
     * 转换
     * 
     */
    public static Object ConventValue(String val,String fieldtype){
    	fieldtype=Util.null2String(fieldtype).trim();
    	if("".equals(fieldtype)){
    		return val;
    	}
    	String[] fieldtypeStr=fieldtype.split(",");
    	if(fieldtypeStr==null||fieldtypeStr.length!=2){
    		return val;
    	}
    	String type=fieldtypeStr[0];
    	int length=Util.getIntValue(fieldtypeStr[1], -1) ;
    	if("0".equals(type)){//字符  有限制长度
    		if(length>=0){
    			return getSubString(val,0,length);
    		}else{
    			return val;
    		}
    	}else if("1".equals(type)){//整数
    		return roundInt(val);
    	}else if("2".equals(type)){//浮点  默认保留两位有效数字
    		if(length==-1){
    			length=2;
    		}
    		return roundStr(val,length);
    		
    	}else{
    		return val;
    	}
    	
    }
    /**
     * java dobule数据转字符串输出
     * @param tempX 需要被转换的数据
     * @return 默认保留4位小数输出
     */
    public static String doubleToStr1(String tempX) {
        double newStemp=roundStr(tempX, 2);
        DecimalFormat df = new DecimalFormat("0.00");
        String newff = df.format(newStemp);
        return newff;
    }
    /**
     * 四舍五入
     * @param v
     * @param scale 精确位数
     */
    public static double roundStr(String v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        try{
        	BigDecimal b = new BigDecimal(v);
            BigDecimal one = new BigDecimal("1");
            return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        }catch(Exception e){
        	
        }
        return 0;
    }
    /*
     * 取整数
     */
    public static int roundInt(String v) {

        try{
        	 BigDecimal b = new BigDecimal(v);
            BigDecimal one = new BigDecimal("1");
            return b.intValue();
        }catch(Exception e){
        	
        }
        return 0;
    }
    
    public static String getSubString(String str,int pstart,int pend){

  	  String resu="";

  	  int beg=0;

  	  int end=0;

  	  int count1=0;

  	  char[] temp=new char[str.length()];

  	  str.getChars(0,str.length(),temp,0);

  	  boolean[] bol=new boolean[str.length()];

  	  for(int i=0;i<temp.length;i++){

  	   bol[i]=false;

  	   if((int)temp[i]>255){//说明是中文

  	    count1++;

  	    bol[i]=true;

  	   }

  	  }

  	  if(pstart>str.length()+count1){

  	   resu=null;

  	  }

  	  if(pstart>pend){

  	   resu=null;

  	  }

  	  if(pstart<1){

  	   beg=0;

  	  }else{

  	   beg=pstart-1;

  	  }

  	  if(pend>str.length()+count1){

  	   end=str.length()+count1;

  	  }else{

  	   end=pend;//在substring的末尾一样

  	  }

  	  //下面开始求应该返回的字符串

  	  if(resu!=null){

  	   if(beg==end){

  	    int count=0;

  	    if(beg==0){

  	     if(bol[0]==true)

  	      resu=null;

  	     else

  	      resu=new String(temp,0,1);

  	    }else{

  	     int len=beg;//zheli

  	     for(int y=0;y<len;y++){//表示他前面是否有中文,不管自己

  	      if(bol[y]==true)

  	       count++;

  	       len--;//想明白为什么len--

  	     }

  	     //for循环运行完毕后，len的值就代表在正常字符串中，目标beg的上一字符的索引值

  	     if(count==0){//说明前面没有中文

  	      if((int)temp[beg]>255)//说明自己是中文

  	       resu=null;//返回空

  	      else

  	       resu=new String(temp,beg,1);

  	     }else{//前面有中文，那么一个中文应与2个字符相对

  	      if((int)temp[len+1]>255)//说明自己是中文

  	       resu=null;//返回空

  	      else

  	       resu=new String(temp,len+1,1);

  	     }

  	    }

  	   }else{//下面是正常情况下的比较

  	    int temSt=beg;

  	    int temEd=end-1;//这里减掉一

  	    for(int i=0;i<temSt;i++){

  	     if(bol[i]==true)

  	      temSt--;

  	    }//循环完毕后temSt表示前字符的正常索引

  	    for(int j=0;j<temEd;j++){

  	     if(bol[j]==true)

  	      temEd--;

  	    }//循环完毕后temEd-1表示最后字符的正常索引

  	    if(bol[temSt]==true)//说明是字符，说明索引本身是汉字的后半部分，那么应该是不能取的

  	    {

  	     int cont=0;

  	     for(int i=0;i<=temSt;i++){

  	      cont++;

  	      if(bol[i]==true)

  	       cont++;

  	     }

  	     if(pstart==cont)//是偶数不应包含,如果pstart<cont则要包含

  	      temSt++;//从下一位开始

  	    }

  	    if(bol[temEd]==true){//因为temEd表示substring 的最面参数，此处是一个汉字，下面要确定是否应该含这个汉字

  	     int cont=0;

  	     for(int i=0;i<=temEd;i++){

  	      cont++;

  	      if(bol[i]==true)

  	       cont++;

  	     }

  	     if(pend<cont)//是汉字的前半部分不应包含

  	      temEd--;//所以只取到前一个

  	    }

  	    if(temSt==temEd){

  	     resu=new String(temp,temSt,1);

  	    }else if(temSt>temEd){

  	     resu=null;

  	    }else{

  	     resu=str.substring(temSt,temEd+1);

  	    }

  	   }

  	  }

  	  return resu;//返回结果

  	 }


}
